let router = require('express').Router()
let db = require('../db')
let bcrypt = require('bcryptjs')

// 注册
router.post('/register', async (req, res, next) => {
    let body = req.body
    if (!body.user_name) return res.fail('用户名不能为空！')
    if (!body.password) return res.fail('密码不能为空！')
    let userList = await db({
        sql: 'select user_name from en_user',
        next
    })
    if (userList.map(item => item.user_name).includes(body.user_name)) return res.fail('用户名被占用！')
    body.password = bcrypt.hashSync(body.password, 10)
    let r = await db({
        sql: 'insert into en_user set ?',
        value: body,
        next
    })
    if (r.affectedRows == 1) res.success('注册成功！')
})

// 登录
router.post('/login', async (req, res, next) => {
    let body = req.body
    if (!body.user_name) return res.fail('用户名不能为空！')
    if (!body.password) return res.fail('密码不能为空！')
    let data = await db({
        sql: 'select * from en_user where user_name = ?',
        value: body.user_name,
        next
    })
    if (!data.length) return res.fail('用户不存在！')
    if (!bcrypt.compareSync(body.password, data[0].password)) return res.fail('用户名或者密码错误！')
    let params = { ...data[0], password: '' }
    let token = require('jsonwebtoken').sign(params, 'yan', { expiresIn: '3h' })
    res.success('登录成功！', token)
})

// 用户信息
router.get('/userInfo', async (req, res, next)=>{
    let data = await db({
        sql: 'select id,user_name,nick_name,email,user_pic from en_user where id = ?',
        value: req.auth.id,
        next
    })
    res.success('操作成功！', data[0])
})

// 用户列表
router.get('/list', async (req, res, next)=>{
    let data = await db({
        sql: 'select id as value, user_name as label from en_user',
        next
    })
    res.success('', data)
})

// 修改用户信息
router.post('/update', async (req, res, next)=>{
    await db({
        sql: 'update en_user set ? where id = ?',
        value: [req.body, req.body.id]
    })
    res.success('操作成功！')
})

// 修改密码
router.post('/modifyPwd', async (req, res, next)=>{
    let user = await db({
        sql: 'select password from en_user where id = ?',
        value: req.auth.id
    })
    if(!bcrypt.compareSync(req.body.oldPwd, user[0].password)){
        return res.fail('原密码不正确！')
    }
    if(req.body.password != req.body.twicePwd){
        return res.fail('两次密码不正确！')
    }
    let r = await db({
        sql: 'update en_user set password = ? where id = ?',
        value: [bcrypt.hashSync(req.body.password, 10), req.auth.id]
    })
    res.success('修改成功，请重新登录！')
})

module.exports = router